import express from 'express';
import http from 'http';
import cors from 'cors';
import dotenv from 'dotenv';

import logger from './utils/logger.js';
import { formatSuccess, formatError } from './utils/helpers.js';
import DatabaseService from './services/DatabaseService.js';
import RoomManager from './services/RoomManager.js';
import MultiplayerGameEngine from './services/MultiplayerGameEngine.js';
import ConnectionManager from './websocket/ConnectionManager.js';
import { createRoomsRouter } from './routes/rooms.js';
import { createGamesRouter } from './routes/games.js';

// 加载环境变量
dotenv.config();

class XuantuotuoMultiplayerServer {
  constructor() {
    this.app = express();
    this.httpServer = http.createServer(this.app);
    this.db = null;
    this.roomManager = null;
    this.gameEngine = null;
    this.connectionManager = null;
    
    this.port = process.env.PORT || 3002;
    this.wsPort = process.env.WS_PORT || 3001;
  }

  async init() {
    try {
      // 初始化数据库服务
      this.db = new DatabaseService();
      
      // 初始化业务服务
      this.roomManager = new RoomManager(this.db);
      this.gameEngine = new MultiplayerGameEngine(this.db);
      
      // 设置中间件
      this.setupMiddleware();
      
      // 设置路由
      this.setupRoutes();
      
      // 初始化WebSocket服务器
      this.setupWebSocketServer();
      
      // 启动清理任务
      this.startCleanupTasks();
      
      logger.info('服务器初始化完成');
      
    } catch (error) {
      logger.error(`服务器初始化失败: ${error.message}`);
      throw error;
    }
  }

  setupMiddleware() {
    // CORS配置
    this.app.use(cors({
      origin: [
        'http://localhost:5173',
        'http://localhost:8080', 
        'http://127.0.0.1:5173',
        'http://localhost:3000'
      ],
      credentials: true
    }));

    // 解析JSON
    this.app.use(express.json({ limit: '10mb' }));
    this.app.use(express.urlencoded({ extended: true, limit: '10mb' }));

    // 请求日志
    this.app.use((req, res, next) => {
      logger.debug(`${req.method} ${req.path} - ${req.ip}`);
      next();
    });
  }

  setupRoutes() {
    // 健康检查
    this.app.get('/health', (req, res) => {
      const stats = {
        server: 'Xuantuotuo Multiplayer Server',
        version: '1.0.0',
        timestamp: new Date().toISOString(),
        uptime: process.uptime(),
        memory: process.memoryUsage(),
        rooms: this.roomManager ? this.roomManager.getStats() : {},
        games: this.gameEngine ? this.gameEngine.getStats() : {},
        connections: this.connectionManager ? this.connectionManager.getStats() : {}
      };
      
      res.json(formatSuccess(stats, '服务器运行正常'));
    });

    // API路由
    this.app.use('/api/rooms', createRoomsRouter(this.roomManager));
    this.app.use('/api/games', createGamesRouter(this.gameEngine));

    // 404处理
    this.app.use('*', (req, res) => {
      res.status(404).json(formatError('NOT_FOUND', '接口不存在'));
    });

    // 错误处理
    this.app.use((error, req, res, next) => {
      logger.error(`请求错误: ${error.message}`, error);
      res.status(500).json(formatError('SERVER_ERROR', '服务器内部错误'));
    });
  }

  setupWebSocketServer() {
    // 创建独立的WebSocket服务器
    const wsServer = http.createServer();
    
    this.connectionManager = new ConnectionManager(
      wsServer, 
      this.roomManager, 
      this.gameEngine
    );

    // 启动WebSocket服务器
    wsServer.listen(this.wsPort, () => {
      logger.info(`WebSocket服务器启动成功，端口: ${this.wsPort}`);
    });

    wsServer.on('error', (error) => {
      logger.error(`WebSocket服务器错误: ${error.message}`);
    });
  }

  startCleanupTasks() {
    // 每5分钟执行一次清理任务
    setInterval(async () => {
      try {
        await this.roomManager.cleanup();
        this.gameEngine.cleanup();
        logger.debug('定时清理任务执行完成');
      } catch (error) {
        logger.error(`清理任务执行失败: ${error.message}`);
      }
    }, 5 * 60 * 1000);
  }

  async start() {
    try {
      await this.init();
      
      // 启动HTTP服务器
      this.httpServer.listen(this.port, () => {
        logger.info(`HTTP服务器启动成功，端口: ${this.port}`);
        logger.info(`WebSocket服务器端口: ${this.wsPort}`);
        logger.info('宣坨坨多人游戏服务器已启动！');
      });

      this.httpServer.on('error', (error) => {
        logger.error(`HTTP服务器错误: ${error.message}`);
      });

      // 处理进程信号
      this.setupGracefulShutdown();
      
    } catch (error) {
      logger.error(`服务器启动失败: ${error.message}`);
      process.exit(1);
    }
  }

  setupGracefulShutdown() {
    const shutdown = async (signal) => {
      logger.info(`收到 ${signal} 信号，开始优雅关闭服务器...`);
      
      try {
        // 关闭HTTP服务器
        this.httpServer.close(() => {
          logger.info('HTTP服务器已关闭');
        });

        // 关闭WebSocket服务器
        if (this.connectionManager) {
          this.connectionManager.close();
        }

        // 关闭数据库连接
        if (this.db) {
          await this.db.close();
        }

        logger.info('服务器优雅关闭完成');
        process.exit(0);
        
      } catch (error) {
        logger.error(`服务器关闭失败: ${error.message}`);
        process.exit(1);
      }
    };

    process.on('SIGTERM', () => shutdown('SIGTERM'));
    process.on('SIGINT', () => shutdown('SIGINT'));
    
    // 处理未捕获的异常
    process.on('uncaughtException', (error) => {
      logger.error('未捕获的异常:', error);
      process.exit(1);
    });

    process.on('unhandledRejection', (reason, promise) => {
      logger.error('未处理的Promise拒绝:', reason);
      process.exit(1);
    });
  }
}

// 启动服务器
if (import.meta.url === `file://${process.argv[1]}`) {
  const server = new XuantuotuoMultiplayerServer();
  server.start();
}

export default XuantuotuoMultiplayerServer;